<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="库房划分" prop="kuQuhua">
        <el-input v-model="queryParams.kuQuhua" placeholder="请输入库房划分" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="机构分类" prop="kuFenlei">
        <el-select v-model="queryParams.kuFenlei" placeholder="请选择机构分类" clearable>
          <el-option v-for="dict in sys_jigou" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="库房名称" prop="kuName">
        <el-input v-model="queryParams.kuName" placeholder="请输入库房名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="库房编号" prop="kuHao">
        <el-input v-model="queryParams.kuHao" placeholder="请输入库房编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="建成时间" prop="kuJianshijian">
        <el-date-picker clearable v-model="queryParams.kuJianshijian" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择建成时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="建设规模" prop="kuGuimo">
        <el-input v-model="queryParams.kuGuimo" placeholder="请输入建设规模" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="投资情况" prop="kuTouzi">
        <el-input v-model="queryParams.kuTouzi" placeholder="请输入投资情况" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="库房类别" prop="kuLeibie">
        <el-select v-model="queryParams.kuLeibie" placeholder="请选择库房类别" clearable>
          <el-option v-for="dict in sys_kclb" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="储存量" prop="kuLiang">
        <el-input v-model="queryParams.kuLiang" placeholder="请输入储存量" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="库房面积" prop="kuMian">
        <el-input v-model="queryParams.kuMian" placeholder="请输入库房面积" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="联系电话" prop="kuDianhua">
        <el-input v-model="queryParams.kuDianhua" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['cangku:cangku:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['cangku:cangku:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['cangku:cangku:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['cangku:cangku:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cangkuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库房id" align="center" prop="kuId" />
      <el-table-column label="库房划分" align="center" prop="kuQuhua" />
      <el-table-column label="机构分类" align="center" prop="kuFenlei">
        <template #default="scope">
          <dict-tag :options="sys_jigou" :value="scope.row.kuFenlei" />
        </template>
      </el-table-column>
      <el-table-column label="库房名称" align="center" prop="kuName" />
      <el-table-column label="库房编号" align="center" prop="kuHao" />
      <el-table-column label="建成时间" align="center" prop="kuJianshijian" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.kuJianshijian, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="建设规模" align="center" prop="kuGuimo" />
      <el-table-column label="投资情况" align="center" prop="kuTouzi" />
      <el-table-column label="库房类别" align="center" prop="kuLeibie">
        <template #default="scope">
          <dict-tag :options="sys_kclb" :value="scope.row.kuLeibie" />
        </template>
      </el-table-column>
      <el-table-column label="储存量" align="center" prop="kuLiang" />
      <el-table-column label="库房面积" align="center" prop="kuMian" />
      <el-table-column label="负责人" align="center" prop="kuFuze" />
      <el-table-column label="联系电话" align="center" prop="kuDianhua" />
      <el-table-column label="库房地址" align="center" prop="kuDizi" />
      <el-table-column label="备      注" align="center" prop="kuBeizu" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['cangku:cangku:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['cangku:cangku:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改仓库表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="cangkuRef" :model="form" :rules="rules" label-width="80px">
<el-form-item label="库房划分" prop="kuQuhua">
  <el-select v-model="form.kuQuhua" placeholder="请选择地区" clearable>
    <el-option v-for="dict in regionOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
  </el-select>
</el-form-item>
        <el-form-item label="机构分类" prop="kuFenlei">
          <el-select v-model="form.kuFenlei" placeholder="请选择机构分类">
            <el-option v-for="dict in sys_jigou" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库房类别" prop="kuLeibie">
          <el-select v-model="form.kuLeibie" placeholder="请选择库房类别">
            <el-option v-for="dict in sys_kclb" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库房名称" prop="kuName">
          <el-input v-model="form.kuName" placeholder="请输入库房名称" />
        </el-form-item>
        <el-form-item label="库房编号" prop="kuHao">
          <el-input v-model="form.kuHao" placeholder="系统自动生成" readonly>
            <template #append>
              <el-button icon="Refresh" @click="generateWarehouseCode" title="重新生成编号"></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="建成时间" prop="kuJianshijian">
          <el-date-picker clearable v-model="form.kuJianshijian" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择建成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="建设规模" prop="kuGuimo">
          <el-input v-model="form.kuGuimo" placeholder="请输入建设规模" />
        </el-form-item>
        <el-form-item label="投资情况" prop="kuTouzi">
          <el-input v-model="form.kuTouzi" placeholder="请输入投资情况" />
        </el-form-item>
        <el-form-item label="储存量" prop="kuLiang">
          <el-input v-model="form.kuLiang" placeholder="请输入储存量" />
        </el-form-item>
        <el-form-item label="库房面积" prop="kuMian">
          <el-input v-model="form.kuMian" placeholder="请输入库房面积" />
        </el-form-item>
        <el-form-item label="负责人" prop="kuFuze">
          <el-input v-model="form.kuFuze" :disabled="true" />
        </el-form-item>
        <el-form-item label="联系电话" prop="kuDianhua">
          <el-input v-model="form.kuDianhua" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="库房地址" prop="kuDizi">
          <el-input v-model="form.kuDizi" placeholder="请输入库房地址" />
        </el-form-item>
        <el-form-item label="备      注" prop="kuBeizu">
          <el-input v-model="form.kuBeizu" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Cangku">
import { listCangku, getCangku, delCangku, addCangku, updateCangku } from "@/api/cangku/cangku"

const { proxy } = getCurrentInstance()
const { sys_kclb, sys_jigou } = proxy.useDict('sys_kclb', 'sys_jigou')

const cangkuList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

import { getInfo } from '@/api/login'


// 新增地区选项
const regionOptions = ref([
  { value: '新疆', label: '新疆维吾尔自治区' },
  { value: '西藏', label: '西藏自治区' },
  { value: '内蒙古', label: '内蒙古自治区' },
  { value: '广西', label: '广西壮族自治区' },
  { value: '宁夏', label: '宁夏回族自治区' }
])

const ming = ref('')
// 获取用户信息
onMounted(async () => {
  try {
    const response = await getInfo()
    ming.value = response.user.nickName
    form.value.kuFuze = ming.value // 同时设置form中的负责人
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
})
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    kuQuhua: null,
    kuFenlei: null,
    kuName: null,
    kuHao: null,
    kuJianshijian: null,
    kuGuimo: null,
    kuTouzi: null,
    kuLeibie: null,
    kuLiang: null,
    kuMian: null,
    kuFuze: null,
    kuDianhua: null,
    kuDizi: null,
    kuBeizu: null
  },
  rules: {
    kuHao: [
      { required: true, message: '库房编号不能为空', trigger: 'blur' },
      // 匹配16位纯数字（3位分类编码 + 10位时间戳 + 3位随机数）
      { pattern: /^\d{16}$/, message: '格式：16位纯数字（如1001625070754123）', trigger: 'blur' }
    ],
    kuName: [
      { required: true, message: '请输入库房名称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度2-20字符', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询仓库表列表 */
function getList() {
  loading.value = true
  listCangku(queryParams.value).then(response => {
    cangkuList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    kuId: null,
    kuQuhua: null,
    kuFenlei: null,
    kuName: null,
    kuHao: null,
    kuJianshijian: null,
    kuGuimo: null,
    kuTouzi: null,
    kuLeibie: null,
    kuLiang: null,
    kuMian: null,
    kuFuze: null,
    kuDianhua: null,
    kuDizi: null,
    kuBeizu: null
  }
  proxy.resetForm("cangkuRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.kuId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}


const CATEGORY_CODE_MAP = {
  '中央': 100,  // 中央机构 → 编码100
  '自治州': 200,  // 地方机构 → 编码200
  '地州': 300,
  '县': 400,  // 自用库房 → 编码300
  // 其他分类...
}
const generateWarehouseCode = () => {
  if (!form.value.kuFenlei || !form.value.kuLeibie) {
    proxy.$modal.msgWarning("请先选择机构分类和库房类别")
    return
  }

  // 1. 获取机构分类编码（从映射表中获取，或根据字典值自定义计算）
  const jigou = sys_jigou.value.find(item => item.value === form.value.kuFenlei.toString())
  const categoryName = jigou?.label || "未知"
  const categoryCode = CATEGORY_CODE_MAP[categoryName] || 0  // 默认0

  // 2. 生成时间戳部分（取当前时间戳后10位，确保唯一性）
  const timestamp = Date.now().toString().slice(-10)  // 例如：1625070754

  // 3. 生成3位随机数（增强唯一性）
  const randomCode = Math.floor(100 + Math.random() * 900)  // 100-999之间的随机数

  // 4. 组合纯数字编号（总长度不超过19位，确保不超过Long.MAX_VALUE）
  // 格式：分类编码(3位) + 时间戳(10位) + 随机数(3位) → 共16位
  form.value.kuHao = `${categoryCode}${timestamp}${randomCode}`  // 例如：1001625070754123
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加仓库表"
  // 设置负责人为当前用户
  form.value.kuFuze = ming.value
  nextTick(() => {
    generateWarehouseCode()
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _kuId = row.kuId || ids.value
  getCangku(_kuId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改仓库表"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["cangkuRef"].validate(valid => {
    if (valid) {
      if (form.value.kuId != null) {
        updateCangku(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCangku(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _kuIds = row.kuId || ids.value
  proxy.$modal.confirm('是否确认删除仓库表编号为"' + _kuIds + '"的数据项？').then(function () {
    return delCangku(_kuIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('cangku/cangku/export', {
    ...queryParams.value
  }, `cangku_${new Date().getTime()}.xlsx`)
}

getList()
</script>
